package message;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class StructMessageBuilderSupplier implements MessageBuilderSupplier{
	protected ArrayList<Function<? super Object, ? extends MessageBuilder>> subBuilders;
	private Supplier<? extends Object> constructor;
	public StructMessageBuilderSupplier(ArrayList<Function<? super Object, ? extends MessageBuilder>> subBuilders, Supplier<? extends Object> constructor) {
		this.subBuilders = subBuilders;
		this.constructor = constructor;
	}
	@Override
	public MessageBuilder get(final Consumer<? super Object> callback) {
		return new AbstractMessageBuilder(callback) { 
			private int iter;
			private int len = subBuilders.size();
			private MessageBuilder[] builders;
			{
				builders = new MessageBuilder[len];
				build = (Message)constructor.get(); 
				for(int i = 0; i<len; i++) {
					builders[i] = subBuilders.get(i).apply(build);
				}
//				rebuild();
			}
//			private void rebuild() {
//				for(int i = 0; i<len; i++) {
//					builders[i] = subBuilders.get(i).apply(build);
//				}
//				build = (Message)constructor.get();
//				iter = 0;
//			}
			@Override
			public boolean read(ByteBuffer byteBuffer) {
				while(iter < len) {
					if(!(builders[iter].read(byteBuffer))) return false;
					iter++;
				}
//				rebuild();
//				return true;
				return super.read(byteBuffer);
			}
		};
	}
}
